package life.majiang.community.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class BtoaEncodeUtil {
//    public static void main(String[] args) {
//        String token = BtoaEncodeUtil.decrypt("JTI2bmFtZSUzRCVFNyVBQiVBNSVFOCU4QSVBQyUyNmFjY291bnRJZCUzRDAxMDAyMTI5JTI2dHlwZSUzRGZhbHNl");
//        System.out.println(token);
//        Map<String, String> map = new HashMap<>();
//        String[] aa = token.split("&");
//
//        for(int i = 0; i < aa.length; i++){
//            String[] bb = aa[i].split("=");
//            map.put(bb[0], bb[1]);
//        }
//
//
//        for (Map.Entry<String, String> entry : map.entrySet()) {
//            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//        }
//    }

    private static String base64hash = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    public static String atob(String inStr) {
        if (inStr == null)
            return null;
        inStr = inStr.replaceAll("\\s|=", "");
        StringBuilder result = new StringBuilder();
        int cur;
        int prev = -1;
        int mod;
        int i = 0;
        while (i < inStr.length()) {
            cur = base64hash.indexOf(inStr.charAt(i));
            mod = i % 4;
            switch (mod) {
                case 0:
                    break;
                case 1:
                    result.append(String.valueOf((char) (prev << 2 | cur >> 4)));
                    break;
                case 2:

                    result.append(String.valueOf((char) ((prev & 0x0f) << 4 | cur >> 2)));
                    break;
                case 3:

                    result.append(String.valueOf((char) ((prev & 3) << 6 | cur)));
                    break;
            }
            prev = cur;
            i++;
        }
        return result.toString();
    }

    public static String decrypt(String str) {
        String atob = BtoaEncodeUtil.atob(str);
        try {
            String decode = URLDecoder.decode(atob, "utf-8");
            return decode;
        } catch (UnsupportedEncodingException e) {
            System.out.println("atob加密函数出现错误。");
        }
        return str;
    }
}
